

#include "AndroidCameraCapture.h"

#define LOG_TAG "AndroidCameraCapture"

extern "C"
JNIEXPORT void JNICALL
Java_com_fan_play_media_capture_VideoCapture_onVideoFrame(JNIEnv *env, jobject thiz,
                                                          jbyteArray y_buf, jbyteArray u_buf,
                                                          jbyteArray v_buf, jint raw_type,
                                                          jint rotation, jboolean is_mirror,
                                                          jlong native_ref) {

}

AndroidCameraCapture::AndroidCameraCapture(CameraDevice *pCapDev) : ICapture(pCapDev) {
  /**
   * 通过NewObject获取Java对象的步骤:
   * 1.获取jclass Java类的包路径 跨线程获取jclass存在问题
   * 2.后去构造函数，使用<init>方法签名表示构造函数，参数签名和其它获取方法ID一样
   * 3.NewObject()传入跟参数签名一样的参数
   */
  auto pEnv = JNIHelper::Instance()->getEnv();
  jclass captureClass = pEnv->FindClass("com/fan/play/media/capture/VideoCapture");

  auto initID = pEnv->GetMethodID(captureClass, "<init>", "(IIIJ)V");
  jobject captureObj = pEnv->NewObject(captureClass, initID, pCapDev->devID, pCapDev->width,
                                       pCapDev->height, reinterpret_cast<jlong>(this));

  //创建全局对象
  _CaptureClass = static_cast<jclass>(pEnv->NewGlobalRef(captureClass));
  _CaptureObj = pEnv->NewGlobalRef(captureObj);

  pCapDev->devState = DeviceState_Init;
}

AndroidCameraCapture::~AndroidCameraCapture() noexcept {
  _pDevice->devState = DeviceState_None;
}

void AndroidCameraCapture::startCapture() {
  if (_pDevice->devState == DeviceState_None)
    return;

  _pDevice->devState = DeviceState_Start;

  auto *pEnv = JNIHelper::Instance()->attachThread();
  auto startID = pEnv->GetMethodID(_CaptureClass, "start", "()Z");
  if (startID && pEnv->CallBooleanMethod(_CaptureObj, startID)) {
    LOG_ERROR("启动失败")
  }
}

void AndroidCameraCapture::stopCapture() {
  if (_pDevice->devState == DeviceState_None)
    return;

  _pDevice->devState = DeviceState_Stop;

  auto *pEnv = JNIHelper::Instance()->attachThread();
  auto stopID = pEnv->GetMethodID(_CaptureClass, "stop", "()V");
  if (stopID) {
    pEnv->CallVoidMethod(_CaptureObj, stopID);
  }

  //删除通过JNIEnv创建的全局对象
  if (!pEnv->IsSameObject(_CaptureObj, nullptr)) {
    pEnv->DeleteGlobalRef(_CaptureObj);
  }

  if (!pEnv->IsSameObject(_CaptureClass, nullptr)) {
    pEnv->DeleteGlobalRef(_CaptureClass);
  }

  JNIHelper::Instance()->detachThread();
}

int32_t AndroidCameraCapture::capacity() {
  return MediaType_Video;
}

const char *AndroidCameraCapture::getClassName() {
  return "AndroidCameraCapture";
}